import { createBrowserPage } from '../browser'
import { Browser, Page } from "puppeteer";
import { lock, unLock, waitFor, waitUnLock } from '@nodejs/redis'
import { delay } from '../util';

/**
 * 微博扫码登陆
 * 返回cookies 和用户信息s's's's's's's's's
 */
export async function weiboLogin(clientId: string, reqId: string) {
    return new Promise(async (resolve, reject) => {
        let page: Page | null = null;
        let browser: Browser | null = null;
        try {
            const url = `https://s.weibo.com/`
            const [_page, _browser] = await createBrowserPage(clientId, url, {
                onResponse: async r => {
                    const url = r.url()
                    if (url.startsWith(`https://v2.qr.weibo.cn/inf/gen`)) {
                        const image = await r.buffer()
                        await lock(reqId, image.toString('utf8'))
                        return;
                    }
                    if (url.startsWith('https://weibo.com/ajax/side/cards/sideInterested')) {
                        const data = await r.json()
                        if (data.ok === 1) {
                            const uid = data.data.uid;
                            await weiboLoginAck(reqId)
                            await lock(`uid.${reqId}`, uid)
                        }
                    }
                    if (url.startsWith(`https://weibo.com/ajax/profile/info`)) {
                        const info = await r.json()
                        await lock(`userInfo.${reqId}`, JSON.stringify(info))
                    }
                }
            });
            page = _page;
            browser = _browser;
            const loginBtn = await page.waitForSelector('div.woo-box-flex.woo-tab-nav > a:nth-child(5)').catch(e => {
                return null;
            });
            if (!loginBtn) return reject(new Error(`login btton not found`))
            await loginBtn.click();
            await getWeiBoLoginQrcode(reqId);
            console.log(`登陆二维码获取成功`)
            // 等待扫码登陆
            await waitUnLock(reqId)
            console.log(`确认扫码成功`)
            const uid = await waitFor(`uid.${reqId}`)
            await page.goto(`https://weibo.com/u/${uid}`, { waitUntil: 'networkidle2' })
            // 获取用户信息
            const userInfo = await waitFor(`userInfo.${reqId}`)
            await unLock(`userInfo.${reqId}`)
            await delay(1000)
            const cookies = await page.cookies()
            await lock(`cookies.${reqId}`, JSON.stringify({
                user: userInfo,
                cookies: cookies
            }))
        } catch (e) {
            return reject(e)
        } finally {
            if (browser) {
                const pages = await browser.pages()
                await Promise.all(pages.map(p => p.close()))
                await browser.close()
            }
        }
    })
}

export async function getWeiBoLoginQrcode(reqId: string): Promise<string> {
    return await waitFor(reqId)
}

export async function weiboLoginAck(reqId: string) {
    await unLock(reqId)
}